package com.qrback.controller;

import com.qrback.entity.User;
import com.qrback.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    // 获取当前用户信息
    @GetMapping("/profile")
    public ResponseEntity<?> getCurrentUserProfile() {
        try {
            // 简化实现，实际项目中需要从JWT令牌中获取当前用户ID
            Integer currentUserId = 1; // 模拟当前用户ID
            User user = userService.getUserById(currentUserId)
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            
            // 返回用户信息，不包含密码
            User userInfo = new User();
            userInfo.setId(user.getId());
            userInfo.setPhone(user.getPhone());
            userInfo.setRole(user.getRole());
            userInfo.setCreatedAt(user.getCreatedAt());
            userInfo.setUpdatedAt(user.getUpdatedAt());
            
            return ResponseEntity.ok(userInfo);
        } catch (Exception e) {
            return ResponseEntity.status(401).body(e.getMessage());
        }
    }

    // 更新用户信息
    @PutMapping("/profile")
    public ResponseEntity<?> updateUserProfile(@RequestBody User userUpdate) {
        try {
            // 简化实现，实际项目中需要从JWT令牌中获取当前用户ID
            Integer currentUserId = 1; // 模拟当前用户ID
            
            // 获取当前用户
            User currentUser = userService.getUserById(currentUserId)
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            
            // 更新用户信息
            if (userUpdate.getPhone() != null) {
                currentUser.setPhone(userUpdate.getPhone());
            }
            // 不允许直接更新角色，只有管理员可以修改角色
            // if (userUpdate.getRole() != null) { currentUser.setRole(userUpdate.getRole()); }
            
            User updatedUser = userService.updateUser(currentUser);
            
            // 返回更新后的用户信息，不包含密码
            User userInfo = new User();
            userInfo.setId(updatedUser.getId());
            userInfo.setPhone(updatedUser.getPhone());
            userInfo.setRole(updatedUser.getRole());
            userInfo.setCreatedAt(updatedUser.getCreatedAt());
            userInfo.setUpdatedAt(updatedUser.getUpdatedAt());
            
            return ResponseEntity.ok(userInfo);
        } catch (Exception e) {
            return ResponseEntity.status(400).body(e.getMessage());
        }
    }
}